package com.wenhai.leetcode.linkedList;

/**
 * @ClassName _234回文链表
 * @Description: https://leetcode-cn.com/problems/palindrome-linked-list/
 * @Author 谢文海
 * @Date 2021/4/5 17:51
 * @Version 1.0
 **/
public class _234回文链表 {

    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        if (head.next.next == null) {
            return head.val == head.next.val;
        }
        ListNode mid = middleListNode(head);
        ListNode rHead = reverseListNode(mid.next);
        ListNode lHead = head;
        while (rHead != null) {
            if (rHead.val != lHead.val) {
                return false;
            }
            rHead = rHead.next;
            lHead = lHead.next;
        }
        return true;
    }

    private ListNode middleListNode(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    private ListNode reverseListNode(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode rev = reverseListNode(head.next);
        head.next.next = head;
        head.next = null;
        return rev;
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1, new ListNode(2, new ListNode(3)));
        new _234回文链表().reverseListNode(listNode);
    }
}
